#include "tansu_internal.h"
#include "tansu_socket.h"
#include "tansu_nwif.h"
#include "tansu_util.h"
#include "tansu_status.h"
#include "tansu_http.h"
#include "tansu_ssdp.h"

static void
dump_response(struct tansu_ssdp_packet *packet)
{
    char *addr;
    struct tansu_keyval *keyval;

    addr = tansu_socket_getaddress(&packet->remote);
    printf("%s\n", addr);
    free(addr);

    printf("\tversion : %s\n", packet->res.version);
    printf("\tstatus  : %d\n", packet->res.status);
    printf("\treadable: %s\n", packet->res.readable);

    STAILQ_FOREACH(keyval, &packet->headers, next) {
        printf("\t%s : %s\n", keyval->key, keyval->value);
    }

    fflush(stdout);
}

static void
process_response(struct tansu_ssdp_packet *packet,
                 void *arg)
{
    dump_response(packet);
}

static void
msearch_finished(struct tansu_ssdp_request *req, void *arg)
{
    struct event_base *evbase = (struct event_base *)arg;
    tansu_ssdp_request_delete(req);
    event_base_loopexit(evbase, NULL);
}

int main(int argc, char *argv[])
{
    struct event_base *evbase;
    struct tansu_ssdp_request *req;
    const char *st = "ssdp:all";
    struct tansu_ssdp_arena arena;
    struct tansu_ssdp_addr mcast_addr;

    evbase = event_base_new();

    tansu_socket_set_addr(AF_INET,
                          &mcast_addr.ss,
                          TANSU_SSDP_IPv4_ADDR,
                          TANSU_SSDP_IPv4_PORT);
    mcast_addr.addr = TANSU_SSDP_IPv4_ADDR;

    if (argc == 2)
        st = argv[1];

    req = tansu_ssdp_request_new(st);
    TASSERT(req);
    req->arena = &arena;
    req->mcast_addr = &mcast_addr;
    req->cb = process_response;
    req->finish_cb = msearch_finished;
    req->finish_cbarg = evbase;

    tansu_ssdp_request_msearch(evbase, req, NULL);

    event_base_dispatch(evbase);
    event_base_free(evbase);

    return 0;
}

